﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using ylyfDataCommon.Exceptions;

namespace ylyfDataCommon.Cypher
{
    public class DESProvider:CypherProvider
    {
        public override string Encryption(string str, string KEY, string IV)
        {
            byte[] inputByte = Encoding.UTF8.GetBytes(str);
            byte[] keyByte = Encoding.UTF8.GetBytes(KEY);
            byte[] IVByte = Encoding.UTF8.GetBytes(IV);

            DESCryptoServiceProvider des = new DESCryptoServiceProvider
            {
                Key = keyByte,
                IV = IVByte
            };
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByte, 0, inputByte.Length);
            cs.FlushFinalBlock();
            return Convert.ToBase64String(ms.ToArray());
        }

        public override string Decryption(string str, string KEY = null, string IV = null)
        {
            if (string.IsNullOrWhiteSpace(KEY)||string.IsNullOrWhiteSpace(IV))
            {
                throw new DecryptionNotSupportException("解密方法需要提供密钥和偏移量");
            }
            byte[] inputByte = Convert.FromBase64String(str);
            byte[] keyByte = Encoding.UTF8.GetBytes(KEY);
            byte[] IVByte = Encoding.UTF8.GetBytes(IV);

            DESCryptoServiceProvider des = new DESCryptoServiceProvider
            {
                Key = keyByte,
                IV = IVByte
            };

            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByte, 0, inputByte.Length);
            cs.FlushFinalBlock();
            //建立StringBuild对象，CreateDecrypt使用的是流对象，必须把解密后的文本变成流对象  
            StringBuilder ret = new StringBuilder();
            return System.Text.Encoding.UTF8.GetString(ms.ToArray());
        }
    }
}